package com.pi.pro.xcmg.am.was.web.cust.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.pi.common.CodesConstants;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.StringUtils;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.entity.TwaDocAsnDetails;
import com.pi.wms.entity.TwaDocAsnHeader;
import com.pi.wms.entity.TwmBasMaterial;
import com.pi.wms.entity.TwtActPalletizeList;
import com.pi.wms.service.AsnDetailsService;
import com.pi.wms.service.AsnService;
import com.pi.wms.service.MaterialService;
import com.pi.wms.service.PalletizeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;


@Slf4j
@Controller
@RequestMapping("/inbound/palletize/ca")
public class CustApplyPalletizeController extends BaseCrudController<TwtActPalletizeList, Long> {

	@Autowired
	private PalletizeService service;

	@Autowired
	private MaterialService materialService;

    @Autowired
    private AsnService asnService;

    @Autowired
    private AsnDetailsService asnDetailsService;
	
	@Override
	protected ICrudService<TwtActPalletizeList, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "palletize";
	}

	@Override
    @ResponseBody
    @JsonView({DataTablesOutput.View.class})
    @GetMapping({"datatablev"})
    public DataTablesOutput<TwtActPalletizeList> datatable(@RequestParam Map<String, Object> q, @Valid DataTablesInput input) {
        this.prepareDatatableConditions(q, input);

        DataTablesOutput<TwtActPalletizeList> output;
        TwmBasMaterial mat=null;
        try {
            output = this.getCrudService().findAll(input, q);
            if ((output!=null) && (output.getData()!=null) && (output.getData().size()>0)){
                for (TwtActPalletizeList p:  output.getData()){
                    mat=this.materialService.lookup(p.getMaterialId());
                    if (mat!=null){
                        p.setUdf10(mat.getName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            output = new DataTablesOutput();
            output.setError("加载表格数据发生异常");
        }
        return output;
    }

    @GetMapping("del/{id}")
    @Override
    public String del(@PathVariable("id") Long id, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        TwtActPalletizeList pal=null;
        String view="";
        Long docdetailsid=null;
        try{
            pal=this.service.findById(id);
            if ((pal!=null) && (pal.getDocumentDetailsId()!=null)){
                docdetailsid=pal.getDocumentDetailsId();
            }
            view=super.del(id,model,request,redirectAttributes);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (docdetailsid==null){
            return view;
        }
        this.refreshDetails(docdetailsid);
        return view;
    }

    @PostMapping("del")
    @Override
    public String del(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
                      RedirectAttributes redirectAttributes) {

        Set<Long> docdeatilsids=new HashSet<>();
        String view="";
        TwtActPalletizeList pal=null;
        if (ids != null && ids.length > 0) {
            try {
                for (Long id : ids) {
                    pal=this.service.findById(id);
                    if ((pal!=null) && (pal.getDocumentDetailsId()!=null)){
                        docdeatilsids.add(pal.getDocumentDetailsId());
                    }
                    if (this.customHandler !=null){
                        this.customHandler.beforeDelete(id,model,request,redirectAttributes);
                    }
                    getCrudService().delete(id);
                    if (this.customHandler !=null){
                        this.customHandler.afterDelete(id,model,request,redirectAttributes);
                    }
                }
                addSuccessMessage(redirectAttributes, "删除数据成功");
            } catch (Exception e) {
                log.error("删除数据失败", e);
                addErrorMessage(redirectAttributes, "删除数据失败");
            }
        }
        if ((docdeatilsids!=null) && (docdeatilsids.size()>0)){
            for (Long detailsid:docdeatilsids){
                this.refreshDetails(detailsid);
            }
        }
        return this.redirect("");
    }

    private String checkAndFlush(TwtActPalletizeList pal){
		String m="";
		if (pal==null){
			m="码盘数据为空";
			return m;
		}
		if (pal.getDocumentDetailsId()==null){
			return m;
		}
		TwaDocAsnHeader header=null;
		TwaDocAsnDetails line=null;
		BigDecimal qtyordered=BigDecimal.ZERO;
		BigDecimal qtyreceived=BigDecimal.ZERO;
		BigDecimal qtypalletized=BigDecimal.ZERO;
		BigDecimal qtyopen=BigDecimal.ZERO;
		try{
			header=this.asnService.findById(pal.getDocumentId());
			if (header==null){
				m="找不到ASN单据,请确认是否已删除.ID:"+String.valueOf(pal.getDocumentId());
				return m;
			}
			if (WmsConstants.ASN_STATUS_CLOSE.equalsIgnoreCase(header.getStatus())){
				m="ASN单据已经完成.单号:"+header.getDocumentNumber();
				return m;
			}
			if (WmsConstants.ASN_STATUS_CANCELL.equalsIgnoreCase(header.getStatus())){
				m="ASN单据已经取消.单号:"+header.getDocumentNumber();
				return m;
			}
			if (WmsConstants.ASN_STATUS_RECEIVE.equalsIgnoreCase(header.getStatus())){
				m="ASN单据已经完全收货.单号:"+header.getDocumentNumber();
				return m;
			}

			line=this.asnDetailsService.findById(pal.getDocumentDetailsId());
			if (line==null){
				m="找不到ASN单行项目,请确认是否已删除.行项ID:"+String.valueOf(pal.getDocumentDetailsId());
				return m;
			}
			if (WmsConstants.ASN_STATUS_CLOSE.equalsIgnoreCase(line.getLineStatus())){
				m="ASN单据已经完成";
				return m;
			}
			if (WmsConstants.ASN_STATUS_CANCELL.equalsIgnoreCase(line.getLineStatus())){
				m="ASN单据已经取消";
				return m;
			}
			if (WmsConstants.ASN_STATUS_RECEIVE.equalsIgnoreCase(line.getLineStatus())){
				m="ASN单据已经完全收货";
				return m;
			}

			qtyordered=BigDecimal.ZERO;
			if (line.getQtyOrdered()!=null){
				qtyordered=line.getQtyOrdered();
			}
			qtyreceived=BigDecimal.ZERO;
			if (line.getQtyReceived()!=null){
				qtyreceived=line.getQtyReceived();
			}
			qtypalletized=BigDecimal.ZERO;
			List<TwtActPalletizeList> pals=this.service.findByDocumentDetailsId(line.getId());
			if (pals!=null){
				for (TwtActPalletizeList pa:pals){
					if (pa==null){
						continue;
					}
					if ((pal.getId()!=null) && (pal.getId().equals(pa.getId()))){
						continue;
					}
					qtyopen=qtyopen.add(pa.getQty());
				}
			}
			qtyopen=qtyopen.add(pal.getQtyEach());

			if (CodesConstants.COMMON_FLAG_NO.equalsIgnoreCase(line.getOverReceiveFlag())){
				if (qtyopen.compareTo(qtyordered)>0){
					m="码盘数量超过订单数量,保存失败.订单数量:"+qtyordered.toPlainString()+",码盘数量:"+qtyopen.toPlainString();
					return m;
				}
				if (qtyopen.compareTo(qtyreceived)<0){
					m="码盘数量少于已收货数量,保存失败.收货数量:"+qtyreceived.toPlainString()+",码盘数量:"+qtyopen.toPlainString();
					return m;
				}
			}
			line.setQtyPalletized(qtyopen);
			line.setQtyPalletizedEach(line.getQtyPalletized());
			if (qtyreceived.compareTo(BigDecimal.ZERO)==0){
				if (line.getQtyPalletized().compareTo(line.getQtyOrdered())<0) {
					line.setLineStatus(WmsConstants.ASN_STATUS_PART_PALLET);
				}else {
					line.setLineStatus(WmsConstants.ASN_STATUS_PALLET);
				}
			}
			if (BigDecimal.ZERO.compareTo(qtyopen)>=0){
				line.setLineStatus(WmsConstants.ASN_STATUS_CANCELL);
			}
			this.asnDetailsService.save(line);
		}catch (Exception e){
			e.printStackTrace();
		}
		return m;
	}

    private void refreshDetails(Long docdetailsid){
        if (docdetailsid==null){
            return;
        }
        TwaDocAsnDetails line=null;
        try{
            line=this.asnDetailsService.findById(docdetailsid);
            if (line==null){
                return;
            }
            BigDecimal qty=BigDecimal.ZERO;
            List<TwtActPalletizeList> pals=this.service.findByDocumentDetailsId(docdetailsid);
            if (pals!=null){
                for (TwtActPalletizeList pal:pals){
                    if (pal==null){
                        continue;
                    }
                    if (pal.getQty()!=null){
                        qty=qty.add(pal.getQty());
                    }
                }
            }
            line.setQtyPalletized(qty);
            line.setQtyPalletizedEach(line.getQtyPalletized());
            if (BigDecimal.ZERO.compareTo(qty)>=0){
                line.setLineStatus(WmsConstants.ASN_STATUS_CANCELL);
            }
            this.asnDetailsService.save(line);
            this.asnService.refreshStatus(line.getHeaderId());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //
    protected String redirect(String relativeUrl) {
        if(!StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
            relativeUrl = "/" + relativeUrl;
        }
        return "redirect:" + this.referUrl() + relativeUrl;
    }

    private String referUrl(){
        return "/inbound/palletize/";
    }

}
